<template>
    <div class="message-log">
        <div class="messag-title">
            <el-select v-model="pushStatus" :placeholder="$t('message.form.selectStatus')" @change="timeChange"
                clearable style="margin-right:16px;width:120px;">
                <el-option v-for="(item, index) in typeList" :key="index" :label="$t(item.label)"
                    :value="item.value"></el-option>
            </el-select>
            <div style="width:230px;">
                <el-date-picker @change="timeChange" v-model="searchTime" type="daterange" range-separator="~"
                    :start-placeholder="$t('message.placeholder.datePickerStart')"
                    :end-placeholder="$t('message.placeholder.datePickerEnd')" value-format="YYYY-MM-DD"
                    :popper-options="{
                        modifiers: [
                            {
                                name: 'flip',
                                options: {
                                    fallbackPlacements: ['bottom'],
                                    allowedAutoPlacements: ['bottom'],
                                }
                            }
                        ]
                    }" />
            </div>
        </div>
        <el-table :data="tableData" header-row-class-name='table-header-class' style="height:calc(100% - 88px);"
            v-loading="tbleLoading">
            <el-table-column :label="$t('message.table.messagePlatform')" prop="platformName">
                <template #default="scope">
                    {{ getLabel(scope.row.platform, platformList) }}
                </template>
            </el-table-column>
            <el-table-column :label="$t('message.table.recipient')" prop="userName"></el-table-column>
            <el-table-column :label="$t('message.table.messageStatus')" prop="pushStatusName">
                <template #default="scope">
                    {{ getLabel(scope.row.pushStatus, typeList) }}
                </template>
            </el-table-column>
            <el-table-column :label="$t('message.table.abnormalInfo')" prop="errorMsg"></el-table-column>
            <el-table-column :label="$t('message.table.operationTime')" prop="createTime"></el-table-column>
            <el-table-column :label="$t('message.table.operation')" width="150" prop="createDate">
                <template #default="scope">
                    <div class="table-action">
                        <el-button type="text" @click="doAction(scope.row)">{{ $t('message.buttons.detail') }}</el-button>
                        <el-button type="text" v-if="['FAILED'].indexOf(scope.row.pushStatus) != -1"
                            @click="reSend(scope.row)">{{ $t('message.buttons.reissue') }}</el-button>
                    </div>
                </template>
            </el-table-column>
            <template #empty>
                <jvs-empty></jvs-empty>
            </template>
        </el-table>
        <div class="message-page-box">
            <el-pagination background layout="prev, pager, next" :total="pageObj.total" :page-size="pageObj.size"
                v-model:current-page="pageObj.current" @current-change="handleCurrentChange" />
        </div>
        <el-dialog v-model="logDetial" class="custom-dialog" width="666px" :show-close='false'
            :close-on-click-modal="false" modal-class="dialog-center" :before-close="handleClose">
            <div class="custom-dialog-header">
                <div class="title-box">
                    <div class="title">日志详情</div>
                </div>
                <svg class="close-icon" @click="handleClose">
                    <use xlink:href="#keowledge-danchuangguanbi1"></use>
                </svg>
            </div>
            <div class="custom-dialog-body">
                <div id="monaco-editor-log" ref="monacoEditor"></div>
            </div>
        </el-dialog>
    </div>
    <el-dialog v-model="logDetial" custom-class="custom-dialog" width="666px" :show-close='false'
        :close-on-click-modal="false" modal-class="dialog-center" :before-close="handleClose">
        <div class="custom-dialog-header">
            <div class="title-box">
                <div class="title">日志详情</div>
            </div>
            <svg class="close-icon" @click="handleClose">
                <use xlink:href="#keowledge-danchuangguanbi1"></use>
            </svg>
        </div>
        <div class="custom-dialog-body">
            <div id="monaco-editor-log" ref="monacoEditor"></div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import {
    ref,
    reactive,
    toRefs,
    watch,
    onMounted,
    nextTick,
    getCurrentInstance
} from 'vue'
import * as monaco from 'monaco-editor'
import { useRouter } from "vue-router"
import { messageSendLog, messageReSend } from '@/api/message'
import { useHookI18n } from '@/hooks/i18n'
const { locale, $t } = useHookI18n()
const router = useRouter();

const emit = defineEmits([""])
const typeList = [{
    label: 'message.typeMenu.success',
    value: 'SUCCESS'
}, {
    label: 'message.typeMenu.fail',
    value: 'FAILED'
}, {
    label: 'message.typeMenu.wait',
    value: 'WAIT'
}]
const platformList = [{
    label: $t('message.platform.email'),
    value: "EMAIL"
}, {
    label: $t('message.platform.enterpriseMessage'),
    value: "WECHAT_WORK_AGENT"
}, {
    label: $t('message.platform.enterpriseRobots'),
    value: "WECHAT_WORK_ROBOT"
}, {
    label: $t('message.platform.wechatAccount'),
    value: "WECHAT_OFFICIAL_ACCOUNT"
}, {
    label: $t('message.platform.dingTalkWorkNotification'),
    value: "DING_TALK_CORP"
}, {
    label: $t('message.platform.dingTalkGroupRobot'),
    value: "DING_TALK_ROBOT"
}, {
    label: $t('message.platform.textMessage'),
    value: "ALI_SMS"
}, {
    label: $t('message.platform.onSitePush'),
    value: "INSIDE_NOTIFICATION"
}]
const pushStatus = ref('')
const searchTime = ref([])
const logDetial = ref(false)
const openItem = ref({})
const monacoEditor = ref()
const props = defineProps({

})
onMounted(() => {
    getList(false)
})
const pageObj = ref({
    current: 1,
    size: 30,
    total: 0
})
const tableData = ref([])
const tbleLoading = ref(false)
function timeChange() {
    getList(true)
}
function getList(flag: boolean) {
    tbleLoading.value = true
    let obj = {
        queryStartTime: null,
        queryEndTime: null
    }
    if (searchTime.value && searchTime.value.length > 0) {
        obj.queryStartTime = searchTime.value[0]
        obj.queryEndTime = searchTime.value[1]
    }
    let oldPage = null
    if (flag) {
        oldPage = JSON.parse(JSON.stringify(pageObj.value))
        pageObj.value.current = 1
    }
    messageSendLog({
        current: pageObj.value.current,
        size: pageObj.value.size,
        pushStatus: pushStatus.value,
        clientCode: 'knowledge',
        ...obj
    }).then(res => {
        if (res.data.code == 0) {
            tableData.value = res.data.data.records
            pageObj.value.total = res.data.data.total
        } else {
            if (flag) {
                pageObj.value.current = oldPage.current
                searchTime.value = []
                searchTime.value.push(proxy.$dayjs().subtract(7, "days").format("YYYY-MM-DD") + ' 00:00:00')
                searchTime.value.push(proxy.$dayjs().format("YYYY-MM-DD") + ' 23:59:59')
            }
        }
    }).finally(res => {
        tbleLoading.value = false
    })
}
function handleCurrentChange() {
    getList(false)
}
function getLabel(val, list) {
    let str = val
    list.forEach((item) => {
        if (item.value == val) {
            str = item.label
        }
    })
    return str
}
function reSend(item) {
    messageReSend({
        hisId: item.id,
        msgType: item.messageType
    }).then(res => {
        if (res.data.code == 0) {
            getList(false)
        }
    })
}
function doAction(row) {
    logDetial.value = true
    openItem.value = row
    nextTick(() => {
        let jsonStr = ''
        jsonStr = JSON.stringify(JSON.parse(openItem.value.messageContent), null, '\t')
        monaco.editor.create(monacoEditor.value, {
            value: jsonStr, // 编辑器初始显示文字
            theme: 'CodeSampleTheme', // 官方自带三种主题vs, hc-black, or vs-dark
            language: 'json', // 语言支持自行查阅demo
            overviewRulerBorder: false, // 滚动是否有边框
            automaticLayout: true, // 自动布局
            readOnly: true, // 是否只读
            minimap: { // 关闭代码缩略图
                enabled: false // 是否启用预览图
            },
            folding: false, // 是否启用代码折叠
            lineNumbers: 'on', // 控制行号的显隐
            scrollBeyondLastLine: false, // 禁用额外滚动区
            scrollbar: {
                verticalScrollbarSize: 4, // 垂直滚动条宽度，默认px
                horizontalScrollbarSize: 4 // 水平滚动条高度
            },
            contextmenu: false // 禁用右键菜单
        })
    })
}
function handleClose() {
    logDetial.value = false
    openItem.value = {}
}
</script>
<style lang="scss" scoped>
.message-log {
    padding: 8px 24px;
    height: 100%;
    box-sizing: border-box;

    .messag-title {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
    }

    ::v-deep(.table-header-class) {
        color: #363B4c;
        @include SourceHanSansCN-Bold;
        font-size: 12px;
        background: #F5F6F7;

        th {
            background: #F5F6F7;
        }
    }

    ::v-deep(.el-scrollbar__view) {
        height: 100%;
    }

    .message-page-box {
        display: flex;
        justify-content: end;
        margin-top: 8px;
    }
}
</style>
<style lang="scss">
#monaco-editor-log {
    border: 1px solid #EEEFF0;
    border-radius: 4px;
    overflow: hidden;
    height: 397px;
}
</style>
